package algorithm;

import java.util.Scanner;
public class MaximumSubarray {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 读取序列长度
        int n = scanner.nextInt();

        // 读取序列
        int[] nums = new int[n];
        for (int i = 0; i < n; i++) {
            nums[i] = scanner.nextInt();
        }

        // 计算最大子段和
        int result = maxSubArray(nums);
        System.out.println(result);

        scanner.close();
    }

    public static int maxSubArray(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int maxSum = nums[0];  // 全局最大值
        int currentSum = nums[0];  // 当前子段和

        for (int i = 1; i < nums.length; i++) {
            // 对于当前元素，要么加入前面的子段，要么重新开始
            currentSum = Math.max(nums[i], currentSum + nums[i]);
            // 更新全局最大值
            maxSum = Math.max(maxSum, currentSum);
        }

        return maxSum;
    }
}
